﻿using System;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;

namespace Editor.ProjectDanmaku.EditorWindow
{
    public class AnimatorControllerCreateWizardWindow : UnityEditor.EditorWindow
    {
        [SerializeField] private AnimatorController templateAnimatorControllerAsset; 
        
        private AnimationClip clipIdle;
        private AnimationClip clipSidling;
        private AnimationClip clipSidled;
        
        private string dirPath;
        
        public static void ShowWindow(string dirPath)
        {
            var window = GetWindow<AnimatorControllerCreateWizardWindow>();
            window.titleContent = new GUIContent("创建者");
            window.Show();
            window.dirPath = dirPath;
        }

        private void OnDisable()
        {
            clipIdle = null;
            clipSidling = null;
            clipSidled = null;
        }

        private void OnGUI()
        {
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            
            GUILayout.Label(
                "Animator Controller Creation 创建者", 
                new GUIStyle("LargeLabel")
                {
                    fontStyle = FontStyle.Bold,
                    fontSize = 16
                });
            
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            
            clipIdle = EditorGUILayout.ObjectField(
                "Idle Clip", clipIdle, typeof(AnimationClip), false) as AnimationClip;
            clipSidling = EditorGUILayout.ObjectField(
                "Sidling Clip", clipSidling, typeof(AnimationClip), false) as AnimationClip;
            clipSidled = EditorGUILayout.ObjectField(
                "Sidled Clip", clipSidled, typeof(AnimationClip), false) as AnimationClip;

            if (clipIdle && clipSidled && clipSidling)
            {
                if (GUILayout.Button("创建 Animator Controller"))
                {
                    var stateMachine = templateAnimatorControllerAsset.layers[0].stateMachine;
                    foreach (var state in stateMachine.states)
                    {
                        if (state.state.name == "Idle") 
                        {
                            stateMachine.states[0].state.motion = clipIdle;
                        } else if (state.state.name == "Sidling") 
                        {
                            stateMachine.states[0].state.motion = clipSidling;
                        } else if (state.state.name == "Sidled") 
                        {
                            stateMachine.states[0].state.motion = clipSidled;
                        }
                    }
                    
                    AssetDatabase.CreateAsset(stateMachine, dirPath + "/AnimatorController.controller");
                }
            }
        }
    }
}